﻿using Datos.Interfaces;
using Entidad;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Dapper;
using DapperExtensions;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;

namespace Datos.Repositories
{
    public class CategoriaRepository : ICategoriaRepository
    {

        private readonly Microsoft.Practices.EnterpriseLibrary.Data.Database _db;


        static CategoriaRepository()
        {
            //DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);
        }

        public CategoriaRepository()
        {
            _db = DatabaseFactory.CreateDatabase("RealConnection");
        }


        public IList<Categoria> FindAll()
        {
            using(IDbConnection conn = _db.CreateConnection())
            {
                const string query = "SELECT * FROM Categoria";
                return conn.Query<Categoria>(query).ToList();
            }
        }

        public IQueryable<Categoria> Find(Expression<Func<Categoria, bool>> predicate)
        {
            throw new NotImplementedException();
        }

        public Categoria FindById(int id)
        {
            using(IDbConnection conn = _db.CreateConnection())
            {
                return conn.Get<Categoria>(id);
            }
        }

        public int Add(Categoria newEntity)
        {
            using(IDbConnection conn = _db.CreateConnection())
            {
                return conn.Insert(newEntity);
            }
        }

        public bool Remove(int id)
        {
            using(IDbConnection conn = _db.CreateConnection())
            {
                bool deleted = conn.Delete(conn.Get<Categoria>(id));
                return deleted;
            }
        }

        public int Modify(Categoria entity)
        {
            using(IDbConnection conn = _db.CreateConnection())
            {
                if (conn.Update(entity))
                {
                    return 1;
                }
                return 0;
            }
        }

       

    }
}
